<template>
  <div class="user-management-wrapper">
    <div class="user-management-container">
      <div class="user-management-header">
        <h1>用户管理</h1>
        <p>管理系统中的所有用户</p>
      </div>
      
      <div class="user-management-content">
        <div class="toolbar">
          <div class="search-box">
            <input 
              v-model="searchKeyword" 
              type="text" 
              placeholder="搜索用户名或邮箱..." 
              @keyup.enter="searchUsers"
            />
            <button @click="searchUsers" class="search-button">搜索</button>
          </div>
          <button @click="showAddUserModal" class="add-user-button">添加用户</button>
        </div>
        
        <div class="user-table-container">
          <table class="user-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>手机号</th>
                <th>角色</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.userId">
                <td>{{ user.userId }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.phone || '-' }}</td>
                <td>{{ getRoleText(user.role) }}</td>
                <td>
                  <span :class="['status-badge', getStatusClass(user.status)]">
                    {{ getStatusText(user.status) }}
                  </span>
                </td>
                <td>{{ formatDate(user.createdTime) }}</td>
                <td>
                  <div class="action-buttons">
                    <button @click="editUser(user)" class="edit-btn">编辑</button>
                    <button 
                      @click="toggleUserStatus(user)" 
                      :class="['status-btn', user.status === 1 ? 'disable' : 'enable']"
                    >
                      {{ user.status === 1 ? '禁用' : '启用' }}
                    </button>
                    <button @click="deleteUser(user.userId)" class="delete-btn">删除</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="pagination">
          <button 
            @click="prevPage" 
            :disabled="currentPage === 1"
            class="pagination-button"
          >
            上一页
          </button>
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          <button 
            @click="nextPage" 
            :disabled="currentPage === totalPages"
            class="pagination-button"
          >
            下一页
          </button>
        </div>
      </div>
      
      <div class="user-management-footer">
        <button @click="goBack" class="back-button">返回首页</button>
      </div>
    </div>
  </div>
  
  <!-- 添加/编辑用户模态框 -->
  <div v-if="showModal" class="modal-overlay" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h2>{{ isEditing ? '编辑用户' : '添加用户' }}</h2>
        <button @click="closeModal" class="close-button">&times;</button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="saveUser" class="user-form">
          <div class="form-group">
            <label for="modalUsername">用户名</label>
            <input 
              id="modalUsername" 
              v-model="userForm.username" 
              type="text" 
              required
            />
          </div>
          
          <div class="form-group" v-if="!isEditing">
            <label for="modalPassword">密码</label>
            <input 
              id="modalPassword" 
              v-model="userForm.password" 
              type="password" 
              required
              minlength="6"
            />
          </div>
          
          <div class="form-group">
            <label for="modalEmail">邮箱</label>
            <input 
              id="modalEmail" 
              v-model="userForm.email" 
              type="email" 
              required
            />
          </div>
          
          <div class="form-group">
            <label for="modalPhone">手机号</label>
            <input 
              id="modalPhone" 
              v-model="userForm.phone" 
              type="tel"
            />
          </div>
          
          <div class="form-group">
            <label for="modalRole">角色</label>
            <select id="modalRole" v-model="userForm.role" required>
              <option :value="0">管理员</option>
              <option :value="1">普通用户</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="modalStatus">状态</label>
            <select id="modalStatus" v-model="userForm.status" required>
              <option :value="1">正常</option>
              <option :value="0">禁用</option>
              <option :value="2">待邮箱验证</option>
            </select>
          </div>
          
          <div class="modal-actions">
            <button type="button" @click="closeModal" class="cancel-button">取消</button>
            <button type="submit" class="save-button">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'

const router = useRouter()
const users = ref([])
const searchKeyword = ref('')
const showModal = ref(false)
const isEditing = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = ref(10)

const userForm = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  role: 1,
  status: 1
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await api.get('/user/list')
    if (response.code === 0) {
      users.value = response.data
      totalPages.value = Math.ceil(users.value.length / pageSize.value)
    } else {
      alert(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    alert('获取用户列表失败，请稍后重试')
  }
}

// 搜索用户
const searchUsers = () => {
  // 简单的前端过滤，实际项目中应该发送到后端处理
  if (!searchKeyword.value) {
    fetchUsers()
    return
  }
  
  // 这里可以添加更复杂的搜索逻辑
  console.log('搜索关键字:', searchKeyword.value)
}

// 显示添加用户模态框
const showAddUserModal = () => {
  isEditing.value = false
  Object.assign(userForm, {
    id: '',
    username: '',
    password: '',
    email: '',
    phone: '',
    role: 1,
    status: 1
  })
  showModal.value = true
}

// 编辑用户
const editUser = (user) => {
  isEditing.value = true
  Object.assign(userForm, {
    id: user.userId,
    username: user.username,
    password: '',
    email: user.email,
    phone: user.phone || '',
    role: user.role,
    status: user.status
  })
  showModal.value = true
}

// 保存用户（添加或编辑）
const saveUser = async () => {
  try {
    let response
    if (isEditing.value) {
      // 编辑用户
      response = await api.post('/user/update', {
        id: userForm.id,
        username: userForm.username,
        email: userForm.email,
        phone: userForm.phone,
        role: userForm.role
      })
    } else {
      // 添加用户
      response = await api.post('/user/add', {
        username: userForm.username,
        password: userForm.password,
        confirmPassword: userForm.password,
        email: userForm.email,
        phone: userForm.phone,
        role: userForm.role
      })
    }
    
    if (response.code === 0) {
      alert(isEditing.value ? '用户更新成功' : '用户添加成功')
      closeModal()
      fetchUsers()
    } else {
      alert(response.message || (isEditing.value ? '用户更新失败' : '用户添加失败'))
    }
  } catch (error) {
    console.error(isEditing.value ? '用户更新失败:' : '用户添加失败:', error)
    alert(isEditing.value ? '用户更新失败，请稍后重试' : '用户添加失败，请稍后重试')
  }
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  try {
    const newStatus = user.status === 1 ? 0 : 1
    const response = await api.post('/user/update/status', null, {
      params: {
        userId: user.userId,
        status: newStatus
      }
    })
    
    if (response.code === 0) {
      alert('用户状态更新成功')
      user.status = newStatus
    } else {
      alert(response.message || '用户状态更新失败')
    }
  } catch (error) {
    console.error('用户状态更新失败:', error)
    alert('用户状态更新失败，请稍后重试')
  }
}

// 删除用户
const deleteUser = async (userId) => {
  if (!confirm('确定要删除这个用户吗？此操作不可恢复！')) {
    return
  }
  
  try {
    const response = await api.post('/user/delete', null, {
      params: {
        userId: userId
      }
    })
    
    if (response.code === 0) {
      alert('用户删除成功')
      fetchUsers()
    } else {
      alert(response.message || '用户删除失败')
    }
  } catch (error) {
    console.error('用户删除失败:', error)
    alert('用户删除失败，请稍后重试')
  }
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
}

// 获取角色文本
const getRoleText = (role) => {
  switch (role) {
    case 0: return '管理员'
    case 1: return '普通用户'
    default: return '未知'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '禁用'
    case 1: return '正常'
    case 2: return '待邮箱验证'
    default: return '未知'
  }
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'disabled'
    case 1: return 'active'
    case 2: return 'pending'
    default: return ''
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 分页相关方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 返回首页
const goBack = () => {
  router.push('/admin')
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management-wrapper {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.user-management-container {
  width: 100%;
  max-width: none;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  box-sizing: border-box;
}

.user-management-header {
  text-align: center;
  margin-bottom: 30px;
}

.user-management-header h1 {
  color: #333;
  font-size: 32px;
  margin-bottom: 10px;
}

.user-management-header p {
  color: #666;
  font-size: 18px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

.search-button, .add-user-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.search-button {
  background: #667eea;
  color: white;
}

.search-button:hover {
  background: #5a6fd8;
}

.add-user-button {
  background: #28a745;
  color: white;
}

.add-user-button:hover {
  background: #218838;
}

.user-table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

.user-table th, .user-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.user-table th {
  background: #e9ecef;
  font-weight: 600;
  color: #495057;
}

.user-table tbody tr:hover {
  background: #e3f2fd;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
}

.status-badge.active {
  background: #e8f5e9;
  color: #388e3c;
}

.status-badge.disabled {
  background: #ffebee;
  color: #d32f2f;
}

.status-badge.pending {
  background: #fff3e0;
  color: #f57c00;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-buttons button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn {
  background: #667eea;
  color: white;
}

.edit-btn:hover {
  background: #5a6fd8;
}

.status-btn.enable {
  background: #28a745;
  color: white;
}

.status-btn.enable:hover {
  background: #218838;
}

.status-btn.disable {
  background: #ffc107;
  color: #212529;
}

.status-btn.disable:hover {
  background: #e0a800;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.pagination-button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-button:hover:not(:disabled) {
  background: #667eea;
  color: white;
}

.pagination-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

.user-management-footer {
  text-align: center;
  margin-top: 30px;
}

.back-button {
  padding: 12px 30px;
  background: #17a2b8;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s;
}

.back-button:hover {
  background: #138496;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-button:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.user-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-form .form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-form .form-group label {
  font-weight: 500;
  color: #333;
}

.user-form .form-group input,
.user-form .form-group select {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.modal-actions .cancel-button,
.modal-actions .save-button {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-button {
  background: #6c757d;
  color: white;
}

.cancel-button:hover {
  background: #5a6268;
}

.save-button {
  background: #667eea;
  color: white;
}

.save-button:hover {
  background: #5a6fd8;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
  }
  
  .search-box {
    width: 100%;
  }
  
  .search-box input {
    flex: 1;
  }
  
  .user-management-container {
    padding: 20px;
  }
  
  .user-table {
    font-size: 14px;
  }
  
  .user-table th, .user-table td {
    padding: 8px 10px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>